package yxy.game.pm2.active.command.belovedhero;

import yxy.apple.util.RandomUtility;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actfavoritewarlord;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_心仪武将活动;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostRandom;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/****************************************
 * @name CMD_Active_心仪武将_ActBelovedHeroRecruit
 * @description 心仪武将心愿招募（单抽  十连抽  以及选择心仪武将）
 * @author 梁健彬
 * @since 2022-07-8
 ***************************************/
@MessageType(proto = Command.ActBelovedHeroRecruit, classtype = ActiveMessage.ActBelovedHeroRecruitRequest.class)
public class CMD_Active_心仪武将_ActBelovedHeroRecruit extends Command<ActiveMessage.ActBelovedHeroRecruitRequest> {

    @Override
    public void execute(MessageSource messageSource, ActiveMessage.ActBelovedHeroRecruitRequest request) throws Exception {
        String playercode = messageSource.getTag();
        int type = request.getType(); //1 单抽  2 十连抽  3 选择武将
        int selectHeroId = request.getSelectHeroId();//选择的英雄id
        ActiveMessage.ActBelovedHeroRecruitResponse.Builder response = ActiveMessage.ActBelovedHeroRecruitResponse.newBuilder();

        try {
            ActiveModule_心仪武将活动 am = ActiveModule_心仪武将活动.get(playercode, false);

            if (am == null) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            if (!am.running()) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            if (type != ActiveModule_心仪武将活动.lotteryOnce && type != ActiveModule_心仪武将活动.lotteryTen && type != ActiveModule_心仪武将活动.selecthero) {
                send(messageSource, response, Result.DataError);
                return;
            }

            ActBelovedHeroHandle heroHandle = new ActBelovedHeroHandle();
            //todo 如果是选择武将
            if (type == ActiveModule_心仪武将活动.selecthero) {
                List<Integer> canSelectHeroList = heroHandle.getCanSelectHeroList();
                //表中不存在该武将返回报错码
                if (!canSelectHeroList.contains(selectHeroId)) {
                    send(messageSource, response, Result.DataError);
                    return;
                }

                //后续可能会需要消耗
                if (am.getSelectid() != 0 && am.getSelectid() != selectHeroId) {
                    actfavoritewarlord heroData = DataCenter.getData(2, actfavoritewarlord.class);
                    Currency heroChangeCost = Currency.create(heroData.getCosttype(), heroData.getCostid(), heroData.getCostnum());

                    //消费
                    try {
                        new CurrencyHandle().cost(playercode, CCReason.心仪武将活动, heroChangeCost);
                    } catch (Exception e) {
                        send(messageSource, response, Result.CostFail);
                        return;
                    }
                }

                am.setSelectid(selectHeroId);
                am.set();
                response.setType(type);
                send(messageSource, response, Result.Success);
                return;
            }

            //todo 如果是单抽或十连抽
            //抽奖的次数
            int times = type == ActiveModule_心仪武将活动.lotteryOnce ? 1 : 10;

            //检查是否可消费
            actfavoritewarlord rewardData = DataCenter.getData(1, actfavoritewarlord.class);
            Currency cost = Currency.create(rewardData.getCosttype(), rewardData.getCostid(), rewardData.getCostnum() * times);
            boolean cangacha = new CurrencyHandle().costCheck(playercode, cost);
            if (!cangacha) {
                send(messageSource, response, new Result(Result.CostFail, cost.getType().getNumber(), cost.getDataId()));//消耗不足
                return;
            }

            //获取抽奖的所有奖品权重，以及心仪武将奖励
            int selectid = am.getSelectid();//心仪武将
            Currency favouriteCurrency = null;

            ArrayList<GhostRandom> grs = new ArrayList<GhostRandom>();//所有物品的权重
            for (int i = 0; i < rewardData.getRewardtype().length; i++) {
                if (rewardData.getRewardtype()[i] == 0) continue;
                Currency cur = Currency.create(rewardData.getRewardtype()[i], rewardData.getRewardid()[i], rewardData.getRewardnum()[i]);
                GhostRandom gr = new GhostRandom(cur, rewardData.getCounter()[i]);
                grs.add(gr);
            }

            actfavoritewarlord heroData = DataCenter.getData(2, actfavoritewarlord.class);
            for (int i = 0; i < heroData.getRewardid().length; i++) {
                if (heroData.getRewardid()[i] == 0) continue;
                if (heroData.getRewardid()[i] == selectid)
                    favouriteCurrency = Currency.create(heroData.getRewardtype()[i], heroData.getRewardid()[i], heroData.getRewardnum()[i]);
            }

            //开始抽奖
            ArrayList<Currency> curs = new ArrayList<Currency>();
            int maxtimes = rewardData.getMaxtimes(); //保底次数
            int cknum = am.getCknum();//已抽次数
            for (int i = 0; i < times; i++) {
                cknum++;
                //保底，重置抽奖必得次数
                if (cknum >= maxtimes) {
                    curs.add(favouriteCurrency);
                    cknum = 0;
                    continue;
                }

                GhostRandom gr = RandomUtility.randomWeight(grs);    //权重随机
                if (gr.getCur().getDataId() == selectid && favouriteCurrency.getNumber() == gr.getCur().getNumber()) {             //随机时抽中，重置抽奖必得次数
                    curs.add(favouriteCurrency);
                    cknum = 0;
                    continue;
                }
                curs.add(gr.getCur());
            }

            //消费
            try {
                new CurrencyHandle().cost(playercode, CCReason.心仪武将活动, cost);
            } catch (Exception e) {
                send(messageSource, response, Result.CostFail);
                return;
            }

            Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
            new CurrencyHandle().addCurrency(playercode, CCReason.心仪武将活动, curs);
            am.setCknum(cknum);
            am.set();

            response.addAllItem(items);
            response.setType(type);

            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, ActiveMessage.ActBelovedHeroRecruitResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}
